const express = require("express")
const pool = require("../utils/DBUtils")
var router = express.Router()

router.post("/login", async (req, res) => {
    let data = req.body
    let account = data.account
    let password = data.password
    let result = await pool.async.query("SELECT * FROM login WHERE `account`=? AND `password`=?", [account,password])
    pool.query(sql, [account, password], (err, result) => {
        if (err) throw err;
        if (result.length > 0) {
            // 判断用户身份
            if (result[0].identity == 'admin') {
                // 生成token
                var token = jwt.sign({
                    identity: result[0].identity,
                    account: result[0].account
                }, 'secret', { expiresIn: '1h' });
                console.log(token);
                res.send({ code: 1, msg: '登录成功', token: token });
            } else if (result[0].identity == 'user') {
                // 生成token
                var token = jwt.sign({
                    identity: result[0].identity,
                    account: result[0].account
                }, 'secret', { expiresIn: '1h' });
                res.send({ code: 2, msg: '登录成功', token: token });
            } else if (result[0].identity == 'root') {
                // 生成token
                var token = jwt.sign({
                    identity: result[0].identity,
                    account: result[0].account
                }, 'secret', { expiresIn: '1h' });
                res.send({ code: 3, msg: '登录成功', token: token });
            }
            // 如果没有登录成功，则返回登录失败
        } else {
            // 判断token
            if (req.headers.authorization == undefined || req.headers.authorization == null) {
                var token = req.headers.authorization.split(' ')[1]; // 获取token
                jwt.verify(token, 'secret', (err, decode) => {
                    if (err) {
                        res.send({ code: 0, msg: '登录失败' });
                    }
                });
            }
        }
    });
})
module.exports = router